<template>
  <div class="retail-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>零售订单管理</h2>
      <p>管理线上线下零售订单，处理退换货等业务</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="配送中" value="shipping" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="退款中" value="refunding" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单渠道">
          <el-select v-model="searchForm.channel" placeholder="请选择渠道" clearable style="width: 150px">
            <el-option label="线上商城" value="online" />
            <el-option label="门店" value="store" />
            <el-option label="微信小程序" value="wechat" />
            <el-option label="APP" value="app" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增订单
        </el-button>
        <el-button type="success" @click="handleBatchExport">
          <el-icon><Download /></el-icon>
          批量导出
        </el-button>
        <el-button type="warning" @click="handleBatchProcess">
          <el-icon><Operation /></el-icon>
          批量处理
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" fixed="left">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="联系电话" width="130" />
        <el-table-column prop="channel" label="订单渠道" width="100">
          <template #default="{ row }">
            <el-tag :type="getChannelTagType(row.channel)">{{ getChannelText(row.channel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.totalAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100" />
        <el-table-column prop="orderTime" label="下单时间" width="160" />
        <el-table-column prop="deliveryAddress" label="配送地址" width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)" v-if="row.status === 'pending'">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="refund" v-if="['paid', 'shipping', 'completed'].includes(row.status)">
                    申请退款
                  </el-dropdown-item>
                  <el-dropdown-item command="cancel" v-if="row.status === 'pending'">
                    取消订单
                  </el-dropdown-item>
                  <el-dropdown-item command="ship" v-if="row.status === 'paid'">
                    发货
                  </el-dropdown-item>
                  <el-dropdown-item command="complete" v-if="row.status === 'shipping'">
                    确认收货
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="80%" :before-close="handleDetailClose">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusTagType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单渠道">
            <el-tag :type="getChannelTagType(currentOrder.channel)">{{ getChannelText(currentOrder.channel) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ currentOrder.orderTime }}</el-descriptions-item>
          <el-descriptions-item label="配送地址" :span="3">{{ currentOrder.deliveryAddress }}</el-descriptions-item>
        </el-descriptions>

        <h4 style="margin: 20px 0 10px 0;">商品明细</h4>
        <el-table :data="currentOrder.items" border>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="小计" width="100">
            <template #default="{ row }">
              ¥{{ row.subtotal.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-summary">
          <el-row :gutter="20">
            <el-col :span="12">
              <h4>支付信息</h4>
              <p>支付方式：{{ currentOrder.paymentMethod }}</p>
              <p>商品金额：¥{{ currentOrder.productAmount.toFixed(2) }}</p>
              <p>运费：¥{{ currentOrder.shippingFee.toFixed(2) }}</p>
              <p>优惠金额：¥{{ currentOrder.discountAmount.toFixed(2) }}</p>
              <p><strong>实付金额：¥{{ currentOrder.totalAmount.toFixed(2) }}</strong></p>
            </el-col>
            <el-col :span="12">
              <h4>物流信息</h4>
              <p>物流公司：{{ currentOrder.logistics?.company || '暂无' }}</p>
              <p>运单号：{{ currentOrder.logistics?.trackingNo || '暂无' }}</p>
              <p>发货时间：{{ currentOrder.logistics?.shipTime || '暂无' }}</p>
              <p>预计送达：{{ currentOrder.logistics?.estimatedTime || '暂无' }}</p>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑订单对话框 -->
    <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑订单' : '新增订单'" width="60%">
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="orderForm.customerName" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="customerPhone">
              <el-input v-model="orderForm.customerPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单渠道" prop="channel">
              <el-select v-model="orderForm.channel" placeholder="请选择渠道" style="width: 100%">
                <el-option label="线上商城" value="online" />
                <el-option label="门店" value="store" />
                <el-option label="微信小程序" value="wechat" />
                <el-option label="APP" value="app" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                <el-option label="微信支付" value="微信支付" />
                <el-option label="支付宝" value="支付宝" />
                <el-option label="银行卡" value="银行卡" />
                <el-option label="现金" value="现金" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="配送地址" prop="deliveryAddress">
          <el-input v-model="orderForm.deliveryAddress" type="textarea" :rows="2" placeholder="请输入配送地址" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="orderForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Operation, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const isEdit = ref(false)
const currentOrder = ref(null)
const selectedOrders = ref([])
const orderFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerName: '',
  status: '',
  channel: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 订单表单
const orderForm = reactive({
  customerName: '',
  customerPhone: '',
  channel: '',
  paymentMethod: '',
  deliveryAddress: '',
  remark: ''
})

// 表单验证规则
const orderRules = {
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  channel: [{ required: true, message: '请选择订单渠道', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  deliveryAddress: [{ required: true, message: '请输入配送地址', trigger: 'blur' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    orderNo: 'RT202401150001',
    customerName: '张三',
    customerPhone: '13800138001',
    channel: 'online',
    totalAmount: 299.00,
    status: 'paid',
    paymentMethod: '微信支付',
    orderTime: '2024-01-15 10:30:00',
    deliveryAddress: '北京市朝阳区建国路88号SOHO现代城',
    productAmount: 280.00,
    shippingFee: 19.00,
    discountAmount: 0.00,
    items: [
      { productName: 'iPhone 15 Pro', specification: '256GB 深空黑色', quantity: 1, unitPrice: 280.00, subtotal: 280.00 }
    ],
    logistics: {
      company: '顺丰速运',
      trackingNo: 'SF1234567890',
      shipTime: '2024-01-15 14:00:00',
      estimatedTime: '2024-01-16 18:00:00'
    }
  },
  {
    id: 2,
    orderNo: 'RT202401150002',
    customerName: '李四',
    customerPhone: '13800138002',
    channel: 'store',
    totalAmount: 158.00,
    status: 'completed',
    paymentMethod: '支付宝',
    orderTime: '2024-01-15 11:15:00',
    deliveryAddress: '上海市浦东新区陆家嘴环路1000号',
    productAmount: 158.00,
    shippingFee: 0.00,
    discountAmount: 20.00,
    items: [
      { productName: '无线蓝牙耳机', specification: '白色', quantity: 2, unitPrice: 89.00, subtotal: 178.00 }
    ],
    logistics: {
      company: '中通快递',
      trackingNo: 'ZT9876543210',
      shipTime: '2024-01-15 16:00:00',
      estimatedTime: '2024-01-16 20:00:00'
    }
  },
  {
    id: 3,
    orderNo: 'RT202401150003',
    customerName: '王五',
    customerPhone: '13800138003',
    channel: 'wechat',
    totalAmount: 89.90,
    status: 'shipping',
    paymentMethod: '微信支付',
    orderTime: '2024-01-15 12:45:00',
    deliveryAddress: '广州市天河区珠江新城花城大道123号',
    productAmount: 79.90,
    shippingFee: 10.00,
    discountAmount: 0.00,
    items: [
      { productName: '智能手环', specification: '黑色 运动版', quantity: 1, unitPrice: 79.90, subtotal: 79.90 }
    ],
    logistics: {
      company: '韵达快递',
      trackingNo: 'YD5555666677',
      shipTime: '2024-01-15 18:00:00',
      estimatedTime: '2024-01-17 12:00:00'
    }
  },
  {
    id: 4,
    orderNo: 'RT202401150004',
    customerName: '赵六',
    customerPhone: '13800138004',
    channel: 'app',
    totalAmount: 1299.00,
    status: 'pending',
    paymentMethod: '银行卡',
    orderTime: '2024-01-15 13:20:00',
    deliveryAddress: '深圳市南山区科技园南区深南大道9999号',
    productAmount: 1299.00,
    shippingFee: 0.00,
    discountAmount: 100.00,
    items: [
      { productName: '笔记本电脑', specification: '16英寸 512GB', quantity: 1, unitPrice: 1399.00, subtotal: 1399.00 }
    ],
    logistics: null
  },
  {
    id: 5,
    orderNo: 'RT202401150005',
    customerName: '孙七',
    customerPhone: '13800138005',
    channel: 'online',
    totalAmount: 45.80,
    status: 'refunded',
    paymentMethod: '支付宝',
    orderTime: '2024-01-15 14:10:00',
    deliveryAddress: '杭州市西湖区文三路508号天苑大厦',
    productAmount: 45.80,
    shippingFee: 0.00,
    discountAmount: 0.00,
    items: [
      { productName: '保温杯', specification: '500ml 不锈钢', quantity: 1, unitPrice: 45.80, subtotal: 45.80 }
    ],
    logistics: {
      company: '申通快递',
      trackingNo: 'ST1111222233',
      shipTime: '2024-01-15 20:00:00',
      estimatedTime: '2024-01-17 10:00:00'
    }
  }
]

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    pending: 'warning',
    paid: 'success',
    shipping: 'primary',
    completed: 'success',
    cancelled: 'info',
    refunding: 'warning',
    refunded: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipping: '配送中',
    completed: '已完成',
    cancelled: '已取消',
    refunding: '退款中',
    refunded: '已退款'
  }
  return statusMap[status] || '未知'
}

// 获取渠道标签类型
const getChannelTagType = (channel) => {
  const channelMap = {
    online: 'primary',
    store: 'success',
    wechat: 'warning',
    app: 'info'
  }
  return channelMap[channel] || 'info'
}

// 获取渠道文本
const getChannelText = (channel) => {
  const channelMap = {
    online: '线上商城',
    store: '门店',
    wechat: '微信小程序',
    app: 'APP'
  }
  return channelMap[channel] || '未知'
}

// 搜索
const handleSearch = () => {
  loading.value = true
  // 模拟搜索延迟
  setTimeout(() => {
    loadData()
    loading.value = false
  }, 500)
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerName: '',
    status: '',
    channel: '',
    dateRange: []
  })
  handleSearch()
}

// 新增订单
const handleAdd = () => {
  isEdit.value = false
  Object.assign(orderForm, {
    customerName: '',
    customerPhone: '',
    channel: '',
    paymentMethod: '',
    deliveryAddress: '',
    remark: ''
  })
  formDialogVisible.value = true
}

// 编辑订单
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(orderForm, {
    id: row.id,
    customerName: row.customerName,
    customerPhone: row.customerPhone,
    channel: row.channel,
    paymentMethod: row.paymentMethod,
    deliveryAddress: row.deliveryAddress,
    remark: row.remark || ''
  })
  formDialogVisible.value = true
}

// 查看订单详情
const handleView = (row) => {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentOrder.value = null
}

// 下拉菜单命令处理
const handleDropdownCommand = async (command, row) => {
  switch (command) {
    case 'refund':
      await handleRefund(row)
      break
    case 'cancel':
      await handleCancel(row)
      break
    case 'ship':
      await handleShip(row)
      break
    case 'complete':
      await handleComplete(row)
      break
  }
}

// 申请退款
const handleRefund = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要为订单 ${row.orderNo} 申请退款吗？`, '确认退款', {
      type: 'warning'
    })
    // 模拟API调用
    ElMessage.success('退款申请已提交')
    loadData()
  } catch {
    // 用户取消
  }
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要取消订单 ${row.orderNo} 吗？`, '确认取消', {
      type: 'warning'
    })
    // 模拟API调用
    ElMessage.success('订单已取消')
    loadData()
  } catch {
    // 用户取消
  }
}

// 发货
const handleShip = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要为订单 ${row.orderNo} 发货吗？`, '确认发货', {
      type: 'info'
    })
    // 模拟API调用
    ElMessage.success('订单已发货')
    loadData()
  } catch {
    // 用户取消
  }
}

// 确认收货
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定订单 ${row.orderNo} 已完成吗？`, '确认完成', {
      type: 'success'
    })
    // 模拟API调用
    ElMessage.success('订单已完成')
    loadData()
  } catch {
    // 用户取消
  }
}

// 批量导出
const handleBatchExport = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要导出的订单')
    return
  }
  ElMessage.success('导出功能开发中...')
}

// 批量处理
const handleBatchProcess = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请选择要处理的订单')
    return
  }
  ElMessage.success('批量处理功能开发中...')
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 提交表单
const handleSubmit = async () => {
  try {
    await orderFormRef.value.validate()
    // 模拟API调用
    ElMessage.success(isEdit.value ? '订单更新成功' : '订单创建成功')
    formDialogVisible.value = false
    loadData()
  } catch {
    // 验证失败
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 300)
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.retail-order-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.amount-text {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.order-summary {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.order-summary h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.order-summary p {
  margin: 5px 0;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .retail-order-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>